﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FSViet.Survey.Helpers;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI.HtmlControls;

namespace FSViet.Survey.Administration.Report
{
	public partial class Default : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
				LoadData( GlobalApplication.GetGuid(Request.QueryString["Id"]));
		}

		DataHelper _dataH = new DataHelper();
		SqlConnection _conn = null;
		DataTable _questions = null;
		void LoadData(Guid id)
		{
			_conn = _dataH.CreateConnection();
			try
			{
				_conn.Open();
				try
				{
					var questions = _dataH.Load(_conn, "SELECT * FROM Questions WHERE CampaignId=@CampaignId AND IsAnswerGroup='False'", 0, 1000,
						_dataH.CreateParam("CampaignId", SqlDbType.Char, GlobalApplication.GetGuidS(id)));
					_questions = questions.Copy();
					DataRow dr;
					int totalQuestion=questions.Rows.Count;
					//while (questionIndex < questions.Rows.Count)
					for (int i = 0; i < totalQuestion; i++)
					{
						dr = questions.Rows[i];
						if (dr["GroupId"] == DBNull.Value 
							|| dr["GroupId"].ToString() == GlobalApplication.GetGuidS(Guid.Empty))
						{
							//render single question
							SurveyFormPanel.Controls.Add(RenderQuestion(dr));
						}
						else
						{
							#region render group question

							//load group info
							var group = _dataH.Load(_conn, "SELECT * FROM Groups WHERE Id=@Id", 0, 100,
								_dataH.CreateParam("Id", SqlDbType.Char, dr["GroupId"]));
							var div = new HtmlGenericControl("div");
							div.InnerHtml = group.Rows[0]["Name"].ToString();
							//add group info
							SurveyFormPanel.Controls.Add(div); 
							var groupId=group.Rows[0]["Id"].ToString();
							//if (dr["AnswerGroupId"] == DBNull.Value
							//|| dr["AnswerGroupId"].ToString() == GlobalApplication.GetGuidS(Guid.Empty))
							//{
							//  //question in group
							//  SurveyFormPanel.Controls.Add(RenderQuestion(dr));
							//}
							//else
							//{
							var questionsInGroup = GetQuestionGroupAnswerGroup(groupId, questions);
							DataRow questionInGroup;
							totalQuestion = questions.Rows.Count; //update total question after filter question in group
							var totalQuestionsInGroup=questionsInGroup.Rows.Count;
							for (int j = 0; j < totalQuestionsInGroup; j++)
							{
								questionInGroup = questionsInGroup.Rows[j];
								if (questionInGroup["AnswerGroupId"] == DBNull.Value
									|| questionInGroup["AnswerGroupId"].ToString() == GlobalApplication.GetGuidS(Guid.Empty))
								{
									//question not use answer group
									SurveyFormPanel.Controls.Add(RenderQuestion(questionInGroup["Name"].ToString() != group.Rows[0]["Name"].ToString(), questionInGroup));
								}
								else
								{
									//question use answer group
									var answerGroupId = questionInGroup["AnswerGroupId"].ToString();
									//filter all question use answer group
									var questionsUseAnswerGroup = GetQuestionGroupAnswerGroup(groupId, answerGroupId, questionsInGroup);
									totalQuestionsInGroup = questionsInGroup.Rows.Count; //update total question in group
									var answerGroup = _dataH.Load(_conn, "SELECT * FROM Questions WHERE Id=@Id", 0, 100,
										_dataH.CreateParam("Id", SqlDbType.Char, answerGroupId));
									//render questions use answer group
									SurveyFormPanel.Controls.Add(GenerateQuestionAnswerGroup(group.Rows[0], answerGroup.Rows[0], questionsUseAnswerGroup));
								}
							}

							#endregion
						}
					}
				}
				finally
				{
					_conn.Close();
				}
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString().Replace("\r\n", "<br/>");
#endif
			}
		}

		/// <summary>
		/// Get question in group
		/// </summary>
		/// <param name="groupId"></param>
		/// <param name="questions"></param>
		/// <returns></returns>
		DataTable GetQuestionGroupAnswerGroup(string groupId, DataTable questions)
		{ return GetQuestionGroupAnswerGroup(groupId, "", questions); }

		/// <summary>
		/// Get question in group an have the same answer group id
		/// </summary>
		/// <param name="groupId"></param>
		/// <param name="answerGroupId"></param>
		/// <param name="questions"></param>
		/// <returns></returns>
		DataTable GetQuestionGroupAnswerGroup(string groupId, string answerGroupId, DataTable questions)
		{
			DataTable result = questions.Copy();
			int index = 0;
			int mappingIndexInSource = 0;
			int totalQuestion = result.Rows.Count;
			DataRow dr;
			while (index < totalQuestion)
			{
				dr = result.Rows[index];
				if (dr["GroupId"].ToString() == groupId)
				{
					if (answerGroupId.Length > 0)
					{
						if (dr["AnswerGroupId"].ToString() == answerGroupId)
						{
							questions.Rows.RemoveAt(mappingIndexInSource);
							index += 1;
						}
						else
						{
							result.Rows.RemoveAt(index);
							totalQuestion = result.Rows.Count;
							mappingIndexInSource += 1;
						}
					}
					else
					{
						questions.Rows.RemoveAt(mappingIndexInSource);
						index += 1;
					}
				}
				else
				{
					result.Rows.RemoveAt(index);
					totalQuestion = result.Rows.Count;
					mappingIndexInSource += 1;
				}
				//if ()
			}

			return result;
		}

		/// <summary>
		/// Get answers by question id
		/// </summary>
		/// <param name="questionId"></param>
		/// <returns></returns>
		DataTable GetAnswers(string questionId)
		{
			return _dataH.Load(_conn, "SELECT * FROM Answers WHERE QuestionId=@QuestionId", 0, 10,
					_dataH.CreateParam("QuestionId", SqlDbType.Char, questionId));
		}
		/// <summary>
		/// render normal question
		/// </summary>
		/// <param name="dr"></param>
		HtmlTable RenderQuestion(DataRow dr)
		{return RenderQuestion(true,dr);}
		HtmlTable RenderQuestion(bool isRenderQuestionContent,DataRow question)
		{
			var table = new HtmlTable();
			table.ID = question["Id"].ToString();

			int renderAnswerMode = 1;
			if (question["RenderAnswerMode"]!=DBNull.Value)
				renderAnswerMode = (int)question["RenderAnswerMode"];

			QuestionTypes type = QuestionTypes.ChoiseOne;
			if (question["QuestionType"] != DBNull.Value)
				type = (QuestionTypes)(int)question["QuestionType"];

			//load answer of question
			var answers = GetAnswers(question["Id"].ToString());
				//_dataH.Load(_conn, "SELECT * FROM Answers WHERE QuestionId=@QuestionId", 0, 10,
				//_dataH.CreateParam("QuestionId", SqlDbType.Char, dr["Id"].ToString()));

			
			if (renderAnswerMode == 1)
			{
				//question
				//answer 1 | answer 2 | answer 3
				#region //render on two line

				var row = new HtmlTableRow();
				var cell = new HtmlTableCell();
				if (isRenderQuestionContent)
				{
					//question content
					cell.InnerHtml = question["Name"].ToString();
					cell.ColSpan = answers.Rows.Count;
					row.Cells.Add(cell);
					table.Rows.Add(row);
				}
				//answers
				row = new HtmlTableRow();
				foreach (DataRow item in answers.Rows)
				{
					cell = new HtmlTableCell();
					cell.InnerHtml = item["Name"].ToString()+": "+GetTotalAnswer(question["Id"].ToString(),item["Id"].ToString()).ToString();
					//cell.Controls.Add(GetAnswerControl(question["Id"].ToString() + "_" + item["Id"].ToString(), type, item["Name"].ToString(), question["Id"].ToString()));
					row.Cells.Add(cell);
				}
				//assign row to table
				table.Rows.Add(row);

				#endregion

				//add question to form
				//SurveyFormPanel.Controls.Add(table);
			}
			else if (renderAnswerMode == 2)
			{ 
				//question
				//answer 1
				//answer 2
				#region //render on two line

				var row = new HtmlTableRow();
				var cell = new HtmlTableCell();
				if (isRenderQuestionContent)
				{
					//question content
					cell.InnerHtml = question["Name"].ToString();
					cell.ColSpan = answers.Rows.Count;
					row.Cells.Add(cell);
					table.Rows.Add(row);
				}
				//answers
				foreach (DataRow item in answers.Rows)
				{
					row = new HtmlTableRow();
					cell = new HtmlTableCell();
					cell.Controls.Add(new Label() { Text = item["Name"].ToString() + ": " + GetTotalAnswer(question["Id"].ToString(), item["Id"].ToString()).ToString() });
					//var answerControl = GetAnswerControl(question["Id"].ToString() + "_" + item["Id"].ToString(),type, item["Name"].ToString(), question["Id"].ToString());
					//if ((bool)item["IsAllowComment"])
					//  answerControl.ID += "_HasComment";
					//cell.Controls.Add(answerControl);
					if ((bool)item["IsAllowComment"])
						cell.Controls.Add(new HyperLink() { NavigateUrl = "Comment.aspx?AnswerId=" + item["Id"].ToString(), Text = "(Trả lời)", Target = "_blank" });

					row.Cells.Add(cell);
					//assign row to table
					table.Rows.Add(row);
				}

				#endregion

				//add question to form
				//SurveyFormPanel.Controls.Add(table);
				//
			}
			else
			{
				//question | answer 1 | answer 2 | answer 3
				#region //render on one line

				var row = new HtmlTableRow();
				var cell = new HtmlTableCell();
				if (isRenderQuestionContent)
				{
					//question content
					cell.InnerHtml = question["Name"].ToString();
					row.Cells.Add(cell);
				}
				//answers
				foreach (DataRow item in answers.Rows)
				{
					cell = new HtmlTableCell();
					cell.InnerHtml = item["Name"].ToString() + ": " + GetTotalAnswer(question["Id"].ToString(), item["Id"].ToString()).ToString();
					//cell.Controls.Add(GetAnswerControl(question["Id"].ToString() + "_" + item["Id"].ToString(),type, item["Name"].ToString(), question["Id"].ToString()));
					row.Cells.Add(cell);
				}
				//assign row to table
				table.Rows.Add(row);

				#endregion

				//add question to form
				//SurveyFormPanel.Controls.Add(table);
			}

			return table;
		}

		int GetTotalAnswer(string questionId,string answerId)
		{
			return (int)_dataH.ExecuteScalar("SELECT COUNT(*) FROM UserAnswers WHERE QuestionId=@QuestionId AND AnswerId=@AnswerId",
				_dataH.CreateParam("QuestionId", SqlDbType.Char, questionId),
				_dataH.CreateParam("AnswerId", SqlDbType.Char, answerId));
		}
		#region generate question group

		HtmlTable GenerateQuestionAnswerGroup(DataRow group, DataRow answerGroup,  DataTable questions)
		{
			HtmlTable result = new HtmlTable();
			HtmlTableRow row;
			HtmlTableCell cell;

			DataTable answers=null;
			if (answerGroup == null)
			{ }
			else
				answers = GetAnswers(answerGroup["Id"].ToString());
				//_dataH.Load(_conn, "SELECT * FROM Answers WHERE QuestionId=@QuestionId", 0, 100,
				//        _dataH.CreateParam("QuestionId", SqlDbType.Char, answerGroup["Id"].ToString()));
			if (group["Name"].ToString() != answerGroup["Name"].ToString())
			{ 
				//generate answer group header
				row = new HtmlTableRow();
				cell = new HtmlTableCell();
				cell.ColSpan = answers.Rows.Count;
				cell.InnerHtml = answerGroup["Name"].ToString();
				row.Cells.Add(cell);
				result.Rows.Add(row);
			}

			//generate
			row = new HtmlTableRow();
			cell = new HtmlTableCell();
			cell.InnerHtml = "&nbsp;";
			row.Cells.Add(cell);
			//generate answer header
			foreach (DataRow item in answers.Rows)
			{
				cell = new HtmlTableCell();
				cell.InnerHtml = item["Name"].ToString();
				cell.Align = "center";
				row.Cells.Add(cell);
			}
			result.Rows.Add(row);
			//generate question
			foreach (DataRow item in questions.Rows)
			{
				result.Rows.Add(GenerateQuestionRow(true, item, answers));	
			}

			return result;
		}

		/// <summary>
		/// Generate question to use answer group
		/// ----------- answer 1 | answer 2 | answer 3
		/// + question     x           x        x
		/// if isUseAnswerGroup do not render answer label 
		/// </summary>
		/// <param name="isUseAnswerGroup"></param>
		/// <param name="question"></param>
		/// <param name="answers"></param>
		/// <returns></returns>
		HtmlTableRow GenerateQuestionRow(bool isUseAnswerGroup,DataRow question, DataTable answers)
		{
			HtmlTableRow result = new HtmlTableRow();
			result.ID = question["Id"].ToString();
			HtmlTableCell cell;
			
			//generate qestion content
			cell = new HtmlTableCell();
			cell.InnerHtml = question["Name"].ToString();
			result.Cells.Add(cell);

			//generate answer
			foreach (DataRow item in answers.Rows)
			{
				cell = new HtmlTableCell();
				cell.InnerHtml = GetTotalAnswer(question["Id"].ToString(),item["Id"].ToString()).ToString();
				//cell.Controls.Add(new RadioButton() { ID = question["Id"].ToString() + "_" + item["Id"].ToString(), Text = isUseAnswerGroup ? "" : item["Name"].ToString(), ToolTip = item["Name"].ToString(), GroupName = question["Id"].ToString() });
				cell.Align = "center";
				result.Cells.Add(cell);
			}

			return result;
		}

		#endregion

		Control GetAnswerControl(string id, QuestionTypes type, string answer, string group)
		{
			Control result = null;
			if (type == QuestionTypes.ChoiseOne)
			{
				result = new RadioButton() { ID = id, Text = answer, GroupName = group };
			}
			else
			{
				result = new CheckBox() { ID = id, Text = answer };
			}
			return result;
		}
	}
}